<?php
	include 'base_config.php';	
	header($contentType_Javascript);
	header($cache);
	header($pragma);
	
	$user = $_REQUEST['username'];
	$userPass = $_REQUEST['userpassword'];
	
	$user =  mysql_real_escape_string($user);
	$userPass = mysql_real_escape_string($userPass);
	$userPass = sha1($salt.$userPass);
	$arr = array();
	
	//Execute the query
	$sql = "SELECT `idUser`, `username`, `userFullName`, `userEmail` FROM user WHERE username = '$user' AND userPassword = '$userPass'";
	
	$rs = mysql_query($sql);
	if (!$rs) {
		die('Invalid query: ' . mysql_error());
	}
	$num_rows = mysql_num_rows($rs);
	// Add the rows to the array
	if ($num_rows < 1) {
		$json = '{"result":"failure"}';
		echo $json;
	} else {
		session_start();
		while($obj = mysql_fetch_object($rs)) {		
			$arr[] = $obj;
		}
		
		$token = generate_token();
		
		$sql = "UPDATE `user` SET `token`='$token' WHERE  `idUser`= " . $arr[0]->idUser;
		$rs = mysql_query($sql);
		if (!$rs) {
			die('Invalid query: ' . mysql_error());
		}
		$remote_addr = $_SERVER['REMOTE_ADDR'];
		if ($remote_addr != '127.0.0.1') {
			$user_agent = mysql_real_escape_string($_SERVER['HTTP_USER_AGENT']);
			$sql = "INSERT INTO `user_log` (`id_user`, `user_agent`, `remote_addr`) VALUES (" . $arr[0]->idUser . ", '" . $user_agent . "', '" . $remote_addr . "')";
			$rs = mysql_query($sql);
			if (!$rs) {
				die('Invalid query: ' . mysql_error());
			}
		}
		$_SESSION['is_logged'] = TRUE;
		setcookie('revanweb', $token, time() + 60*60*24*30, '/');
		
		$json = '{"result":"success","user":' . json_encode($arr).'}';	
		//$json = '{"user":' . json_encode($arr).'}';	
		$json = substr($json, 0, strlen($json) - 3);
		$json = $json . ',"SESSION_ID":"' . session_id() . '"}]}';
		echo $json;
	}
	mysql_close($connect);